package vg.modules.notepad.components.connectorComponent;

import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;

/**
 * This class realizes comboxBox for graphs.
 * @author tzolotuhin
 */
public class GraphComboBox {
	public static final int DEF_GRAPH = 1;
	//-------------------------------------------
	private final JComboBox comboBox;
	private final List<Object>objects;
	private final List<String>titles;
	// Mutex
	private final Object theMutexObject;
	/**
	 * Constructor.
	 */
	public GraphComboBox() {
		// init mutex
		this.theMutexObject = new Object();
		// init components
		this.comboBox = new JComboBox();
		// init data
		this.objects = new ArrayList<Object>();
		this.titles = new ArrayList<String>();
	}
	public void addItem(final Object obj, final String title) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				synchronized (theMutexObject) {
					objects.add(obj);
					titles.add(title);
					comboBox.addItem(title);
					if(objects.size() == 1) {
						comboBox.setSelectedIndex(0);
					}
				}
			}
		});
	}
	public Object getSelectedObject() {
		synchronized (theMutexObject) {
			int index = this.comboBox.getSelectedIndex();
			if(index >= 0 && index < this.objects.size()) {
				return(this.objects.get(index));
			}
			return(null);					
		}
	}
	public String getSelectedTitle() {
		synchronized (theMutexObject) {
			int index = this.comboBox.getSelectedIndex();
			if(index >= 0 && index < this.titles.size()) {
				return(this.titles.get(index));
			}
			return(null);
		}
	}
	public void selectObject(final Object obj) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				synchronized (theMutexObject) {
				int i = 0;
				for(Object buf : objects) {
					if(buf == obj || buf.equals(obj)) {
						comboBox.setSelectedIndex(i);
						return;
					}
					i++;
				}
				}
			}
		});
	}
	public void addActionListener(ActionListener listener) {
		synchronized (theMutexObject) {
			this.comboBox.addActionListener(listener);
		}
	}
	public void removeAllItems() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				synchronized (theMutexObject) {
					titles.clear();
					comboBox.removeAllItems();
					objects.clear();
				}
			}
		});
	}
	public JComponent getView() {
		return(this.comboBox);
	}
}
